<template>
    {{ formData }}
    <AButton
        @click="
            operationType = 'create';
            state.formData = { ...initFormData };
            modalVisible = true;
        "
        type="primary"
        shape="circle"
    >
        <template #icon>
            <PlusOutlined />
        </template>
    </AButton>
    <ATable :pagination="false" :scroll="{ x: 1920 }" :columns="columns" :dataSource="state.dataSource.map((item, index) => ({ ...item, key: index }))">
        <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'type'">
                <ATag v-if="record.type === 1" color="success">网站</ATag>
                <ATag v-if="record.type === 2" color="cyan">APP</ATag>
                <ATag v-if="record.type === 3" color="blue">小程序</ATag>
            </template>
            <template v-if="column.dataIndex === 'focus_img'">
                <AImage :src="`${baseUrl}${record.focus_img}`" :width="40" :height="40" />
            </template>
            <template v-if="column.dataIndex === 'sort'">
                <AInputNumber
                    ref="sortInputRef"
                    v-if="state.showSortInput && state.operatedRecord._id === record._id"
                    type="number"
                    @blur="confirmSortChange"
                    @pressEnter="confirmSortChange"
                    v-model:value="state.operatedRecord.sort"
                />
                <div v-else style="cursor: pointer">
                    <span>{{ record.sort }}</span>
                    <AButton
                        @click="
                            state.showSortInput = true;
                            handleSortInputFocus();
                            state.operatedRecord = record;
                        "
                        type="link"
                    >
                        <template #icon>
                            <EditOutlined />
                        </template>
                    </AButton>
                </div>
            </template>
            <template v-if="column.dataIndex === 'status'">
                <ASwitch
                    @change="
                        checked => {
                            state.operatedRecord = record;
                            statusChange(checked);
                        }
                    "
                    v-model:checked="record.status"
                    :checkedValue="1"
                    :unCheckedValue="0"
                    checkedChildren="可用"
                    unCheckedChildren="禁用"
                />
            </template>
            <template v-if="column.dataIndex === 'operation'">
                <AButton
                    @click="
                        operationType = 'update';
                        state.formData = record;
                        state.operatedRecord = record;
                        modalVisible = true;
                    "
                    type="primary"
                    >编辑</AButton
                >
                <APopconfirm @confirm="handleDelete(record)" :title="`确定删除${record.title}吗？`">
                    <AButton type="danger">删除</AButton>
                </APopconfirm>
            </template>
        </template>
    </ATable>
    <AModal @ok="confirmForm" v-model:visible="modalVisible" :title="`${operationType === 'create' ? '添加' : '编辑'}`" :width="600">
        <ARow>
            <ACol span="21">
                <AForm @finish="confirmForm" ref="formRef" :model="state.formData" v-bind="{ labelCol: { span: 6 }, wrapperCol: { span: 18 } }">
                    <AFormItem name="title" label="轮播名" :rules="[{ required: true, message: '请输入轮播名' }]">
                        <AInput v-model:value="state.formData.title" placeholder="请输入轮播名" />
                    </AFormItem>
                    <AFormItem name="status" label="轮播状态">
                        <ASwitch
                            :checkedValue="1"
                            :unCheckedValue="0"
                            v-model:checked="state.formData.status"
                            checkedChildren="可用"
                            unCheckedChildren="禁用"
                        />
                    </AFormItem>
                    <AFormItem name="type" label="轮播类型">
                        <ASelect v-model:value="state.formData.type">
                            <ASelectOption :value="1"> 网站 </ASelectOption>
                            <ASelectOption :value="2"> APP </ASelectOption>
                            <ASelectOption :value="3"> 小程序 </ASelectOption>
                        </ASelect>
                    </AFormItem>
                    <AFormItem name="link_type" label="连接类型">
                        <ASelect v-model:value="state.formData.link_type">
                            <ASelectOption :value="1"> 路由 </ASelectOption>
                            <ASelectOption :value="2"> 外链 </ASelectOption>
                        </ASelect>
                    </AFormItem>
                    <AFormItem name="route_type" label="路由类型">
                        <ASelect v-model:value="state.formData.route_type">
                            <ASelectOption :value="0"> 无 </ASelectOption>
                            <ASelectOption :value="1"> push </ASelectOption>
                            <ASelectOption :value="2"> replace </ASelectOption>
                        </ASelect>
                    </AFormItem>
                    <AFormItem name="focus_img" label="图片">
                        <CustomUpload v-model:image="state.formData.focus_img" />
                    </AFormItem>
                    <AFormItem name="link" label="跳转链接">
                        <AInput v-model:value="state.formData.link" placeholder="请输入跳转链接" />
                    </AFormItem>
                    <AFormItem name="sort" label="排序号">
                        <AInput type="number" v-model:value="state.formData.sort" placeholder="请输排序号" />
                    </AFormItem>
                </AForm>
            </ACol>
            <ACol span="3"> </ACol>
        </ARow>
    </AModal>
</template>

<script setup>
import { PlusOutlined, EditOutlined } from "@ant-design/icons-vue";
import { reactive, ref, toRefs } from "vue";
import { createBannerApi, deleteBannerApi, getBannerApi, updateBannerApi } from "@/api/banner";
import { message } from "ant-design-vue";
import CustomUpload from "@/components/CustomUpload";
import { throttle } from "@/utils";
const columns = [
    {
        dataIndex: "_id",
        title: "ID",
        width: 0,
        ellipsis: true
    },
    {
        dataIndex: "title",
        title: "轮播名",
        width: 10,
    },
    {
        dataIndex: "type",
        title: "类型",
        width: 10,
    },
    {
        dataIndex: "link_type",
        title: "链接类型",
        customRender({ text }) {
            return text === 1 ? "路由" : text === 2 ? "外链" : "";
        },
        width: 10,
    },
    {
        dataIndex: "route_type",
        title: "路由类型",
        customRender({ text }) {
            return text === 0 ? "无" : text === 1 ? "push" : text === 2 ? "replace" : "";
        },
        width: 10,
    },
    {
        dataIndex: "focus_img",
        title: "图片",
        width: 10,
    },
    {
        dataIndex: "link",
        title: "跳转链接",
        width: 10,
    },
    {
        dataIndex: "sort",
        title: "排序号",
        width: 10,
    },
    {
        dataIndex: "status",
        title: "状态",
        width: 10,
        customRender: ({ text }) => (text ? "可用" : "不可用"),
    },
    {
        title: "操作",
        width: 10,
        dataIndex: "operation",
        fixed: "right",
    },
];
const initFormData = {
    title: "",
    type: 1,
    focus_img: "",
    link: "",
    sort: 100,
    status: 1,
    link_type: 1,
    route_type: 0,
};
const state = reactive({
    dataSource: [],
    formData: { ...initFormData },
    operatedRecord: {},
    accessList: [],
    bannerAccessKeys: [],
    expandedKeys: [],
    requestingKeys: [],
    showSortInput: false,
});
const modalVisible = ref(false);
const operationType = ref("create");
const formRef = ref();
const getBanner = () => {
    return getBannerApi().then(res => {
        if (res.code === 200) {
            state.dataSource = reactive(res.data);
            return res.data;
        }
    });
};
getBanner();
const confirmForm = () => {
    formRef.value.validate().then(result => {
        if (operationType.value === "create") {
            createBannerApi(result).then(async res => {
                if (res.code === 200) {
                    await getBanner();
                    message.success("添加成功");
                    modalVisible.value = false;
                }
            });
        }
        if (operationType.value === "update") {
            updateBannerApi({ _id: state.operatedRecord._id, ...result }).then(async res => {
                if (res.code === 200) {
                    await getBanner();
                    message.success("更新成功");
                    modalVisible.value = false;
                }
            });
        }
    });
};
const handleDelete = record => {
    deleteBannerApi({ _id: record._id }).then(async res => {
        if (res.code === 200) {
            await getBanner();
            message.success("删除成功");
        }
    });
};
const baseUrl = process.env.VUE_APP_BASEURL;
const statusChange = checked => {
    updateBannerApi({ _id: state.operatedRecord._id, status: checked }).then(async res => {
        if (res.code === 200) {
            await getBanner();
            message.success("更新成功");
            modalVisible.value = false;
        }
    });
};
const updateSortThrottle = throttle(() => {
    updateBannerApi({ _id: state.operatedRecord._id, sort: state.operatedRecord.sort }).then(async res => {
        if (res.code === 200) {
            await getBanner();
            message.success("更新成功");
            state.showSortInput = false;
        }
    });
});
const confirmSortChange = () => updateSortThrottle();
const sortInputRef = ref();
const handleSortInputFocus = () => {
    setTimeout(() => {
        sortInputRef.value.focus();
    });
};
</script>

<style scoped lang="scss"></style>
